<!doctype html><html lang=zh-hans>
<head>
<meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<meta http-equiv=x-ua-compatible content="IE=edge">
<meta name=author content="小李刀刀">
<meta name=description content="Spiral 框架包含了一系列组件，以通过不同来源的临时或永久令牌认证用户身份，并安全地管理用户上下文。 用户认证组件不强制执行任何特定的用户实体接口，也不会将应用程序限制在 HTTP 应用类型（GRPC 应用也可以进行认证）。 工作原理 认证组件会为 Spiral\Auth\AuthContextInterface 创建一个 IoC 作用域，指向当前授权的行为人（用户、API 客户">
<meta name=theme-color content="#3f51b5">
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin=anonymous>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-1/css/all.min.css integrity="sha256-4w9DunooKSr3MFXHXWyFER38WmPdm361bQS/2KUWZbU=" crossorigin=anonymous>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin=anonymous>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/tomorrow-night.min.css crossorigin=anonymous title=hl-light>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/tomorrow-night.min.css crossorigin=anonymous title=hl-dark disabled>
<script src=https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.1.2/lazysizes.min.js integrity="sha256-Md1qLToewPeKjfAHU1zyPwOutccPAm5tahnaw7Osw0A=" crossorigin=anonymous async></script>
<link rel=stylesheet href="https://fonts.font.im/css?family=Source+Code+Pro:300,400,500,600,700&subset=latin-ext&display=swap">
<link rel=stylesheet href=/css/academic.css>
<script>(function(b,d,e,a,g){b[a]=b[a]||[],b[a].push({'gtm.start':(new Date).getTime(),event:'gtm.js'});var f=d.getElementsByTagName(e)[0],c=d.createElement(e),h=a!='dataLayer'?'&l='+a:'';c.async=!0,c.src='https://www.googletagmanager.com/gtm.js?id='+g+h,f.parentNode.insertBefore(c,f)})(window,document,'script','dataLayer','GTM-5KZH8N7')</script>
<link rel=manifest href=/index.webmanifest>
<link rel=icon type=image/png href=/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_32x32_fill_lanczos_center_3.png>
<link rel=apple-touch-icon type=image/png href=/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_192x192_fill_lanczos_center_3.png>
<link rel=canonical href=https://studyspiral.cn/docs/security/authentication/>
<meta property="twitter:card" content="summary">
<meta property="og:site_name" content="Spiral中文网">
<meta property="og:url" content="https://studyspiral.cn/docs/security/authentication/">
<meta property="og:title" content="用户认证 | Spiral中文网">
<meta property="og:description" content="Spiral 框架包含了一系列组件，以通过不同来源的临时或永久令牌认证用户身份，并安全地管理用户上下文。 用户认证组件不强制执行任何特定的用户实体接口，也不会将应用程序限制在 HTTP 应用类型（GRPC 应用也可以进行认证）。 工作原理 认证组件会为 Spiral\Auth\AuthContextInterface 创建一个 IoC 作用域，指向当前授权的行为人（用户、API 客户"><meta property="og:image" content="https://studyspiral.cn/images/logo.svg">
<meta property="twitter:image" content="https://studyspiral.cn/images/logo.svg"><meta property="og:locale" content="zh-Hans">
<meta property="article:published_time" content="2020-04-12T23:24:38+08:00">
<meta property="article:modified_time" content="2020-08-28T15:38:18+08:00">
<script src=https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.js integrity="sha256-5VhCqFam2Cn+yjw61zbBNrbHVJ6SRydPeKopYlngbiQ=" crossorigin=anonymous></script>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.css integrity="sha256-zQ0LblD/Af8vOppw18+2anxsuaz3pWYyVWi+bTvTH8Q=" crossorigin=anonymous>
<script>window.addEventListener("load",function(){window.cookieconsent.initialise({palette:{popup:{background:"#3f51b5",text:"#fff"},button:{background:"#fff",text:"#3f51b5"}},theme:"classic",content:{message:"本网站使用cookies来确保您在本网站上获得最佳体验。",dismiss:"知道了!",link:"了解更多",href:"https://www.cookiesandyou.com"}})})</script>
<title>用户认证 | Spiral中文网</title>
</head>
<body id=top data-spy=scroll data-offset=70 data-target=#TableOfContents>
<aside class=search-results id=search>
<div class=container>
<section class=search-header>
<div class="row no-gutters justify-content-between mb-3">
<div class=col-6>
<h1>搜索</h1>
</div>
<div class="col-6 col-search-close">
<a class=js-search href=#><i class="fas fa-times-circle text-muted" aria-hidden=true></i></a>
</div>
</div>
<div id=search-box>
<input name=q id=search-query placeholder=搜索... autocapitalize=off autocomplete=off autocorrect=off spellcheck=false type=search>
</div>
</section>
<section class=section-search-results>
<div id=search-hits>
</div>
</section>
</div>
</aside>
<nav class="navbar navbar-expand-lg navbar-light compensate-for-scrollbar" id=navbar-main>
<div class=container>
<div class="d-none d-lg-inline-flex">
<a class=navbar-brand href=/><img src=/images/logo.svg alt=Spiral中文网>Spiral中文网</a>
</div>
<button type=button class=navbar-toggler data-toggle=collapse data-target=#navbar-content aria-controls=navbar aria-expanded=false aria-label=切换导航>
<span><i class="fas fa-bars"></i></span>
</button>
<div class="navbar-brand-mobile-wrapper d-inline-flex d-lg-none">
<a class=navbar-brand href=/><img src=/images/logo.svg alt=Spiral中文网>Spiral中文网</a>
</div>
<div class="navbar-collapse main-menu-item collapse justify-content-end" id=navbar-content>
<ul class="navbar-nav d-md-inline-flex">
<li class=nav-item>
<a class=nav-link href=/docs/basics/quick-start/><span>教程</span></a>
</li>
<li class=nav-item>
<a class="nav-link active" href=/docs/><span>文档</span></a>
</li>
<li class=nav-item>
<a class=nav-link href=/post/><span>文章</span></a>
</li>
</ul>
</div>
<ul class="nav-icons navbar-nav flex-row ml-auto d-flex pl-md-2">
<li class=nav-item>
<a class="nav-link js-search" href=#><i class="fas fa-search" aria-hidden=true></i></a>
</li>
</ul>
</div>
</nav>
<div class="container-fluid docs">
<div class="row flex-xl-nowrap">
<div class="col-12 col-md-3 col-xl-2 docs-sidebar">
<form class="docs-search d-flex align-items-center">
<button class="btn docs-toggle d-md-none p-0 mr-3" type=button data-toggle=collapse data-target=#docs-nav aria-controls=docs-nav aria-expanded=false aria-label="Toggle section navigation">
<span><i class="fas fa-bars"></i></span>
</button>
<input name=q type=search class=form-control placeholder=搜索... autocomplete=off>
</form>
<nav class="collapse docs-links" id=docs-nav>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/extension/dotenv/>Dotenv</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/>总览</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse show">
<li>
<a href=/docs/>Spiral介绍</a>
</li>
<li>
<a href=/docs/about/contributing/>贡献指引</a>
</li>
<li>
<a href=/docs/about/semver/>版本说明</a>
</li>
<li>
<a href=/docs/about/license/>授权协议</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/http/psr-15/>定制 PSR-15 处理器</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/start/install/>快速开始</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/start/install/>安装指引</a>
</li>
<li>
<a href=/docs/start/workers/>应用工作进程</a>
</li>
<li>
<a href=/docs/start/structure/>应用程序结构</a>
</li>
<li>
<a href=/docs/start/configuration/>默认配置</a>
</li>
<li>
<a href=/docs/start/commands/>控制台命令</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/basics/quick-start/>入门基础</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/basics/quick-start/>上手指南</a>
</li>
<li>
<a href=/docs/basics/scaffolding/>脚手架</a>
</li>
<li>
<a href=/docs/basics/prototype/>原型开发辅助</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/framework/design/>核心框架</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/framework/design/>设计理念</a>
</li>
<li>
<a href=/docs/framework/application-server/>应用服务器</a>
</li>
<li>
<a href=/docs/framework/config/>配置对象</a>
</li>
<li>
<a href=/docs/framework/kernel/>内核与环境</a>
</li>
<li>
<a href=/docs/framework/container/>容器</a>
</li>
<li>
<a href=/docs/framework/bootloaders/>引导程序</a>
</li>
<li>
<a href=/docs/framework/scopes/>IoC 作用域</a>
</li>
<li>
<a href=/docs/framework/memory/>静态高速缓存</a>
</li>
<li>
<a href=/docs/framework/finalizers/>终结器</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/cookbook/annotated-routes/>速查手册</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/cookbook/annotated-routes/>注解式路由</a>
</li>
<li>
<a href=/docs/cookbook/injector/>容器注入器</a>
</li>
<li>
<a href=/docs/cookbook/domain-core/>领域内核、控制器</a>
</li>
<li>
<a href=/docs/cookbook/golang-library/>Golang服务集成</a>
</li>
<li>
<a href=/docs/cookbook/custom-dispatcher/>自定义调度器</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/component/files/>常用组件</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/component/files/>文件和目录</a>
</li>
<li>
<a href=/docs/component/reactor/>代码生成</a>
</li>
<li>
<a href=/docs/component/tokenizer/>静态分析工具</a>
</li>
<li>
<a href=/docs/component/metrics/>应用指标</a>
</li>
<li>
<a href=/docs/component/data-grid/>数据网格</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/console/configuration/>控制台</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/console/configuration/>安装和配置</a>
</li>
<li>
<a href=/docs/console/commands/>用户命令</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/http/configuration/>HTTP</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/http/configuration/>安装配置</a>
</li>
<li>
<a href=/docs/http/lifecycle/>请求生命周期</a>
</li>
<li>
<a href=/docs/http/request-response/>请求和响应</a>
</li>
<li>
<a href=/docs/http/routing/>路由</a>
</li>
<li>
<a href=/docs/http/errors/>错误页面</a>
</li>
<li>
<a href=/docs/http/middleware/>中间件</a>
</li>
<li>
<a href=/docs/http/golang/>Golang 中间件</a>
</li>
<li>
<a href=/docs/http/cookies/>Cookies</a>
</li>
<li>
<a href=/docs/http/session/>Session</a>
</li>
<li>
<a href=/docs/http/csrf/>CSRF 防护</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/security/encrypter/>安全</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse show">
<li>
<a href=/docs/security/encrypter/>数据加密</a>
</li>
<li>
<a href=/docs/security/validation/>数据验证</a>
</li>
<li>
<a href=/docs/security/rbac/>基于角色的权限控制</a>
</li>
<li class=active>
<a href=/docs/security/authentication/>用户认证</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/filters/configuration/>请求过滤</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/filters/configuration/>安装和配置</a>
</li>
<li>
<a href=/docs/filters/filter/>过滤器</a>
</li>
<li>
<a href=/docs/filters/composite/>复合过滤器</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/database/configuration/>数据库</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/database/configuration/>安装与配置</a>
</li>
<li>
<a href=/docs/database/access/>访问数据</a>
</li>
<li>
<a href=/docs/database/isolation/>逻辑隔离</a>
</li>
<li>
<a href=/docs/database/query-builders/>查询构造器</a>
</li>
<li>
<a href=/docs/database/transactions/>Transactions</a>
</li>
<li>
<a href=/docs/database/introspection/>Schema Introspection</a>
</li>
<li>
<a href=/docs/database/declaration/>Declaration</a>
</li>
<li>
<a href=/docs/database/migrations/>Migrations</a>
</li>
<li>
<a href=/docs/database/errata/>Errata</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/cycle/configuration/>Cycle ORM</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/cycle/configuration/>Configuration</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/queue/configuration/>队列任务</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/queue/configuration/>Configuration</a>
</li>
<li>
<a href=/docs/queue/scraper/>网站爬虫</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/views/configuration/>视图</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/views/configuration/>Configuration</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/stempler/configuration/>Stempler 模板</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/stempler/configuration/>Configuration</a>
</li>
<li>
<a href=/docs/stempler/directives/>Directives</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>国际化</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>GRPC</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>事件广播</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>调试及性能</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>扩展</a>
</div>
</nav>
</div>
<div class="d-none d-xl-block col-xl-2 docs-toc">
<ul class="nav toc-top">
<li><a href=# id=back_to_top class=docs-toc-title>在本页</a></li>
</ul>
<nav id=TableOfContents>
<ul>
<li><a href=#工作原理>工作原理</a></li>
<li><a href=#安装和配置>安装和配置</a>
<ul>
<li><a href=#session-令牌存储>Session 令牌存储</a></li>
<li><a href=#数据库令牌存储>数据库令牌存储</a></li>
</ul>
</li>
<li><a href=#行为人提供器和令牌数据>行为人提供器和令牌数据</a></li>
<li><a href=#认证用户>认证用户</a>
<ul>
<li><a href=#用户登录>用户登录</a></li>
<li><a href=#检查登录>检查登录</a></li>
<li><a href=#用户注销>用户注销</a></li>
</ul>
</li>
<li><a href=#rbac-安全组件>RBAC 安全组件</a></li>
<li><a href=#防火墙中间件>防火墙中间件</a>
<ul>
<li><a href=#自定义防火墙>自定义防火墙</a></li>
</ul>
</li>
</ul>
</nav>
</div>
<main class="col-12 col-md-9 col-xl-8 py-md-3 pl-md-5 docs-content" role=main>
<article class=article>
<div class="alert alert-warning" role=alert>
官方文档中文版翻译工作仍在进行中，欢迎 <a href=/post/join-translation/>参与翻译</a>。
</div>
<div class=docs-article-container>
<h1>用户认证</h1>
<div class=article-style>
<p>Spiral 框架包含了一系列组件，以通过不同来源的临时或永久令牌认证用户身份，并安全地管理用户上下文。</p>
<blockquote>
<p>用户认证组件不强制执行任何特定的用户实体接口，也不会将应用程序限制在 HTTP 应用类型（GRPC 应用也可以进行认证）。</p>
</blockquote>
<h2 id=工作原理>工作原理</h2>
<p>认证组件会为 <code>Spiral\Auth\AuthContextInterface</code> 创建一个 IoC 作用域，指向当前授权的行为人（用户、API 客户端）。行为人由 <code>Spiral\Auth\TokenInterface</code> 从 <code>Spiral\Auth\ActorProviderInterface</code> 进行获取。</p>
<p>Token 由 <code>Spiral\Auth\TokenStorageInterface</code> 管理，并且始终包含有效数据（例如 <code>['UserId' => $id]</code>、LDAP 证书等）。Token 数据会被 <code>Spiral\Auth\ActorProviderInterface</code> 用于查询当前应用程序用户。</p>
<p>Token 存储既可以把 token 存储于外部源（例如数据库、Redis 或文件），也可以即时解码。为了便于使用，Spiral 框架默认包含了多套 token 实现。</p>
<blockquote>
<p>你可以在同一个应用程序中同时使用多套 token 和 actor 提供程序。</p>
</blockquote>
<h2 id=安装和配置>安装和配置</h2>
<p>要在 Web 应用程序模板创建的应用中安装用户认证组件，可以执行：</p>
<pre><code class=language-bash>$ composer require spiral/auth spiral/auth-http
</code></pre>
<p><code>spiral/auth</code> 包提供了不与任何调度方式（HTTP、GRPC）关联的标准接口，而 <code>spiral/auth-http</code> 则包含了用于 Web 应用的 HTTP 中间件、令牌传输（Cookie、Header）以及防火墙组件。</p>
<p>要激活组件，需要添加 <code>Spiral\Bootloader\Auth\HttpAuthBootloader</code> 引导程序：</p>
<pre><code class=language-php>[
    // ...
    Framework\Auth\HttpAuthBootloader::class,
    // ...
]
</code></pre>
<p>安装完成后，必须要选择用什么方式来存储用户认证令牌。</p>
<h3 id=session-令牌存储>Session 令牌存储</h3>
<p>如果想用 PHP session 来存储令牌，首先确保 <code>spiral/session</code> 组件已安装，并用 <code>Spiral\Bootloader\Auth\TokenStorage\SessionTokensBootloader</code> 来启用 session 存储：</p>
<pre><code class=language-php>[
    // ...
    Framework\Auth\HttpAuthBootloader::class,
    Framework\Auth\TokenStorage\SessionTokensBootloader::class,
    // ...
]
</code></pre>
<h3 id=数据库令牌存储>数据库令牌存储</h3>
<p>Spiral 也可以把通过 Cycle ORM 把令牌存储在数据库中，要使用这种方式，需要启用 <code>Spiral\Bootloader\Auth\TokenStorage\CycleTokensBootloader</code> 引导程序：</p>
<pre><code class=language-php>[
    // ...
    Framework\Auth\HttpAuthBootloader::class,
    Framework\Auth\TokenStorage\CycleTokensBootloader::class,
    // ...
]
</code></pre>
<p>此外还必须运行控制台命令 <code>cycle:sync</code> 来生成和执行数据库迁移，以便在数据库中创建所需的表：</p>
<pre><code class=language-php>$ php app.php migrate:init
$ php app.php cycle:migrate -v -r
</code></pre>
<h2 id=行为人提供器和令牌数据>行为人提供器和令牌数据</h2>
<p>下一步是配置从令牌数据中获取行为人/用户的方式，为了实现这个功能，需要实现和注册 <code>Spiral\Auth\ActorProviderInterface</code> 接口。</p>
<pre><code class=language-php>interface ActorProviderInterface
{
    public function getActor(TokenInterface $token): ?object;
}
</code></pre>
<p>在本文中，我们以 Cycle 实体和数据仓库为例：</p>
<pre><code class=language-php>namespace App\Database;

use Cycle\Annotated\Annotation as Cycle;

/**
 * @Cycle\Entity(repository=&quot;Repository/UserRepository&quot;)
 * @Cycle\Table(indexes={
 *     @Cycle\Table\Index(columns={&quot;username&quot;}, unique=true)
 * })
 */
class User
{
    /**
     * @Cycle\Column(type = &quot;primary&quot;)
     */
    public $id;

    /** @Cycle\Column(type=&quot;string&quot;) */
    public $name;

    /** @Cycle\Column(type=&quot;string&quot;) */
    public $username;

    /** @Cycle\Column(type=&quot;string&quot;) */
    public $password;
}
</code></pre>
<p>在 <code>UserRepository</code> 上实现 <code>ActorProviderInterface</code> 接口：</p>
<pre><code class=language-php>namespace App\Database\Repository;

use Cycle\ORM\Select\Repository;
use Spiral\Auth\ActorProviderInterface;
use Spiral\Auth\TokenInterface;

class UserRepository extends Repository implements ActorProviderInterface
{
    public function getActor(TokenInterface $token): ?object
    {
        if (!isset($token-&gt;getPayload()['userID'])) {
            return null;
        }

        return $this-&gt;findByPK($token-&gt;getPayload()['userID']);
    }
}
</code></pre>
<p>在准备工作完成后，先来创建一个用户：</p>
<pre><code class=language-php>public function index(Transaction $t)
{
    $u = new User();
    $u-&gt;name = 'Antony';
    $u-&gt;username = 'username';
    $u-&gt;password = password_hash('password', PASSWORD_DEFAULT);

    $t-&gt;persist($u)-&gt;run();
}
</code></pre>
<p>在你的应用程序中创建和启用一个引导程序，并在引导程序中注册行为人提供器来启用它：</p>
<pre><code class=language-php>namespace App\Bootloader;

use App\Database\Repository\UserRepository;
use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Bootloader\Auth\AuthBootloader;

class UserBootloader extends Bootloader
{
    public function boot(AuthBootloader $auth)
    {
        $auth-&gt;addActorProvider(UserRepository::class);
    }
}
</code></pre>
<h2 id=认证用户>认证用户</h2>
<p>用户认证过程通过 <code>Spiral\Auth\AuthContextInterface</code> 进行。你可以通过方法注入获得实现该接口的当前认证上下文对象实例。</p>
<pre><code class=language-php>public function index(AuthContextInterface $auth)
{
    // 使用认证上下文
}
</code></pre>
<blockquote>
<p>注意：不要在单例服务中存储 <code>AuthContextInterface</code>，你可以参考上面我们是如何传递这个对象的。</p>
</blockquote>
<p>除此之外，你也可以使用 <code>Spiral\Auth\AuthScope</code>, 这是可以存储在单例服务中的，或者使用原型开发辅助里的 <code>auth</code> 属性。</p>
<pre><code class=language-php>namespace App\Controller;

use Spiral\Prototype\Traits\PrototypeTrait;

class HomeController
{
    use PrototypeTrait;

    public function index()
    {
        dump($this-&gt;auth);
    }
}
</code></pre>
<h3 id=用户登录>用户登录</h3>
<p>实现用户登录需要我们创建一个登录表单以及相应的请求过滤器。</p>
<pre><code class=language-php>namespace App\Request;

use Spiral\Filters\Filter;

class LoginRequest extends Filter
{
    public const SCHEMA = [
        'username' =&gt; 'data:username',
        'password' =&gt; 'data:password'
    ];

    public const VALIDATES = [
        'username' =&gt; ['notEmpty'],
        'password' =&gt; ['notEmpty']
    ];
}
</code></pre>
<p>Create login method in the controller dedicated to authentication:
在控制器中创建一个专门用于用户认证的登录方法，</p>
<pre><code class=language-php>public function login(LoginRequest $login)
{
    if (!$login-&gt;isValid()) {
        return [
            'status' =&gt; 400,
            'errors' =&gt; $login-&gt;getErrors()
        ];
    }

    // application specific login logic
    $user = $this-&gt;users-&gt;findOne(['username' =&gt; $login-&gt;getField('username')]);
    if (
        $user === null
        || !password_verify($login-&gt;getField('password'), $user-&gt;password)
    ) {
        return [
            'status' =&gt; 404,
            'error'  =&gt; '用户不存在'
        ];
    }

    // 创建令牌
}
</code></pre>
<p>要为上面的请求认证用户，必须创建和你选择的 <code>ActorProviderInterface</code> 兼容的数据对象（<code>['UserId' => $id]</code>），要实现这个，我们会用到 <code>AuthContextInterface</code> 接口的实例以及 <code>TokenStorageInterface</code> 的实例。这两个对象，分别可以通过原型开发辅助的 <code>auth</code> 和 <code>authTokens</code> 属性来访问到：</p>
<pre><code class=language-php>public function login(LoginRequest $login)
{
    // ... 代码略，见上文

    // 创建令牌
    $this-&gt;auth-&gt;start(
        $this-&gt;authTokens-&gt;create(['userID' =&gt; $user-&gt;id])
    );

    return [
        'status'  =&gt; 200,
        'message' =&gt; '认证成功！'
    ];
}
</code></pre>
<p>这样，就完成了用户登录认证。</p>
<h3 id=检查登录>检查登录</h3>
<p>要检查当前用户的登录状态，只要检查认证上下文（auth context）拥有一个不为空的行为人（actor）即可：</p>
<pre><code class=language-php>public function index()
{
    if ($this-&gt;auth-&gt;getActor() === null) {
        throw new ForbiddenException();
    }
    
    dump($this-&gt;auth-&gt;getActor());
}
</code></pre>
<blockquote>
<p>你可以使用 RBAC 安全组件来同时进行用户认证和用户鉴权。</p>
</blockquote>
<h3 id=用户注销>用户注销</h3>
<p>要注销当前用户的登录，可以调用认证上下文或者认证作用域（AuthScope）的 <code>close</code> 方法：</p>
<pre><code class=language-php>public function logout()
{
    $this-&gt;auth-&gt;close();
}
</code></pre>
<h2 id=rbac-安全组件>RBAC 安全组件</h2>
<p>你可以使用已经认证的用户作为 RBAC 安全组件的行为人，如果需要这样使用，需确保你的用户实体（例如 <code>App\Database\User</code>）实现 <code>Spiral\Security\ActorInterface</code> 接口：</p>
<pre><code class=language-php>namespace App\Database;

use Cycle\Annotated\Annotation as Cycle;
use Spiral\Security\ActorInterface;

/**
 * @Cycle\Entity(repository=&quot;Repository/UserRepository&quot;)
 * @Cycle\Table(indexes={
 *     @Cycle\Table\Index(columns={&quot;username&quot;}, unique=true)
 * })
 */
class User implements ActorInterface
{
    /**
     * @Cycle\Column(type = &quot;primary&quot;)
     */
    public $id;

    /** @Cycle\Column(type=&quot;string&quot;) */
    public $name;

    /** @Cycle\Column(type=&quot;string&quot;) */
    public $username;

    /** @Cycle\Column(type=&quot;string&quot;) */
    public $password;

    public function getRoles(): array
    {
        return ['user'];
    }
}
</code></pre>
<p>并且启用 <code>Spiral\Bootloader\Auth\SecurityActorBootloader</code> 引导程序把两个组件（用户认证组件、RBAC 安全组件）连接起来：</p>
<pre><code class=language-php>[
    // ...
    Framework\Auth\SecurityActorBootloader::class,
    // ...
]
</code></pre>
<h2 id=防火墙中间件>防火墙中间件</h2>
<p>你可以把防火墙中间件绑定到特定路由目标，以避免未授权的访问。</p>
<p>默认情况下，Spiral 只提供了一个防火墙，它会将未认证的用户重定向到其它 url:</p>
<pre><code class=language-php>use Spiral\Auth\Middleware\Firewall\OverwriteFirewall;

// ...

(new Route('/account/&lt;controller&gt;/&lt;action&gt;', $accountTarget))
        -&gt;withMiddleware(new OverwriteFirewall(new Uri('/account/login')));
</code></pre>
<h3 id=自定义防火墙>自定义防火墙</h3>
<p>要实现自己的防火墙中间件，只要扩展 <code>Spiral\Auth\Middleware\Firewall\AbstractFirewall</code> 即可：</p>
<pre><code class=language-php>final class OverwriteFirewall extends AbstractFirewall
{
    protected function denyAccess(Request $request, RequestHandlerInterface $handler): Response
    {
        // 用户未认证
        return $handler-&gt;handle($request);
    }
}
</code></pre>
</div>
<div class=article-widget>
<div class=post-nav>
<div class=post-nav-item>
<div class=meta-nav>上一页</div>
<a href=/docs/security/rbac/ rel=next>基于角色的权限控制</a>
</div>
<div class=post-nav-item>
<div class=meta-nav>下一页</div>
<a href=/docs/stempler/directives/ rel=prev>Directives</a>
</div>
</div>
</div>
</div>
<div class=body-footer>
<p>最近更新于 2020-08-28</p>
<p class=edit-page>
<a href=https://github.com/krwu/spiraldocs/edit/feat/chinese/zh_CN/security/authentication.md>
<i class="fas fa-pen pr-2"></i>编辑本页
</a>
</p>
</div>
</article>
<footer class=site-footer>
<p class=powered-by><span class=copyright>© 2019 - 2021 <a href=https://studyspiral.cn/>StudySpiral</a> All rights reserved.</span>
</p>
<p class=powered-by>
<a href=http://www.beian.miit.gov.cn/ target=_blank rel="noopener noreferer">粤ICP备14011364号</a>
<a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=44030402001866" target=_blank rel="noopener noreferer"><img style=display:inline-block src=/img/gaba.png>粤公网安备 44030402001866号</a>
</p>
<p id=webify class=powered-by style=display:none>[<a href=https://webify.cloudbase.net/ target=_blank rel=noopener>CloudBase Webify</a>] 提供网站托管服务</p>
<script async defer>window.addEventListener('DOMContentLoaded',()=>{const{host:a}=window.location;a.toLocaleLowerCase()==='docs.studyspiral.cn'&&(document.getElementById('webify').style.display='block')})</script>
</footer>
</main>
</div>
</div>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.4/imagesloaded.pkgd.min.js integrity="sha256-lqvxZrPLtfffUl2G/e7szqSvPBILGbwmsGE1MKlOi0Q=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.6/isotope.pkgd.min.js integrity="sha256-CBrpuqrMhXwcLLUd5tvQ4euBHCdh7wGlDfNz8vbu/iI=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/highlight.min.js integrity="sha256-eOgo0OtLL4cdq7RdwRUiGKLX9XsIJ7nGhWEKbohmVAQ=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/languages/go.min.js></script>
<script>const code_highlighting=!0</script>
<script>const isSiteThemeDark=!1</script>
<script>const search_config={indexURI:"/index.json",minLength:1,threshold:.3},i18n={no_results:"没有找到结果",placeholder:"搜索...",results:"搜索结果"},content_type={post:"文章",project:"项目",publication:"出版物",talk:"演讲"}</script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/anchor-js/4.1.1/anchor.min.js integrity="sha256-pB/deHc9CGfFpJRjC43imB29Rse8tak+5eXqntO94ck=" crossorigin=anonymous></script>
<script>anchors.add()</script>
<script id=search-hit-fuse-template type=text/x-template>
      <div class="search-hit" id="summary-{{key}}">
      <div class="search-hit-content">
        <div class="search-hit-name">
          <a href="{{relpermalink}}">{{title}}</a>
          <div class="article-metadata search-hit-type">{{type}}</div>
          <p class="search-hit-description">{{snippet}}</p>
        </div>
      </div>
      </div>
    </script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js integrity="sha256-VzgmKYmhsGNNN4Ph1kMW+BjoYJM2jV5i4IlFoeZA9XI=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js integrity="sha256-4HLtjeVgH0eIB3aZ9mLYF6E8oU5chNdjU6p6rrXpl9U=" crossorigin=anonymous></script>
<script src=/js/academic.min.6f1005d1a84220e2f466ff3d8e712f31.js></script>
<div id=modal class="modal fade" role=dialog>
<div class=modal-dialog>
<div class=modal-content>
<div class=modal-header>
<h5 class=modal-title>引用</h5>
<button type=button class=close data-dismiss=modal aria-label=Close>
<span aria-hidden=true>&#215;</span>
</button>
</div>
<div class=modal-body>
<pre><code class="tex hljs"></code></pre>
</div>
<div class=modal-footer>
<a class="btn btn-outline-primary my-1 js-copy-cite" href=# target=_blank>
<i class="fas fa-copy"></i> 复制
</a>
<a class="btn btn-outline-primary my-1 js-download-cite" href=# target=_blank>
<i class="fas fa-download"></i> 下载
</a>
<div id=modal-error></div>
</div>
</div>
</div>
</div>
</body>
</html>